package com.volunteer.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.volunteer.config.RedisComponent;
import com.volunteer.mapper.ProvincialCityMapper;
import com.volunteer.model.ProvincialCity;
import com.volunteer.service.ProvincialCityService;
import com.volunteer.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author willow
 * @date 2019年03月13日
 */
@Service
public class ProvincialCityServiceImpl implements ProvincialCityService {
    private static final String URLJDAREA = "https://d.jd.com/area/get";// 获取地区链接
    @Autowired
    private ProvincialCityMapper provincialCityMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional
    public Result catchJDData(Integer level, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<ProvincialCity> provincialCityList = provincialCityMapper.selectByLevel(level);
        PageInfo<ProvincialCity> pageInfo = new PageInfo<>(provincialCityList);
        int i = 1;
        for (ProvincialCity provincialCity : pageInfo.getList()) {
            System.out.println("------------------------------------------------------------第" + i + "个");
            this.initChildArea(provincialCity.getId(), level);
            System.out.println("------------------------------------------------------------剩余" + (provincialCityList.size() - i) + "个");
            i++;
        }
        return ResponseResult.genSuccessResult("抓取成功");
    }

    @Override
    public Result getProvincial(Long id) {
        // 查询缓存中是否存在
        Object object = redisUtil.getMapString(Constants.REDIS_PROVINCIAL, id.toString());
        List<ProvincialCity> provincialCityList;
        if (null != object) {
            provincialCityList = JSON.parseArray(object.toString(), ProvincialCity.class);
        } else {
            provincialCityList = provincialCityMapper.selectByParentId(id);
            // 将记录存入缓存
            Map<String, Object> mapObject = new HashMap<>();
            mapObject.put(id.toString(), JSON.toJSONString(provincialCityList));
            redisUtil.addObject(Constants.REDIS_PROVINCIAL, mapObject);
        }
        return ResponseResult.genSuccessResult(provincialCityList);
    }

    /**
     * 获取各省下级地区
     *
     * @param parentId 所属地区ID
     * @param level    地区层级，省级：0，市级：1，...
     */
    private void initChildArea(Long parentId, int level) {
        String text = HttpUtils.sendGet(URLJDAREA, "fid=" + parentId);
        if (!StringUtils.isEmpty(text)) {
            JSONArray jsonArray = JSON.parseArray(text);
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Long id = jsonObject.getLong("id");
                    String name = jsonObject.getString("name");
                    ProvincialCity selectProvincialCity = provincialCityMapper.selectByPrimaryKey(id);
                    if (selectProvincialCity == null) {
                        ProvincialCity provincialCity = new ProvincialCity();
                        provincialCity.setId(id);
                        provincialCity.setName(name);
                        provincialCity.setParentId(parentId);
                        provincialCity.setLevel(level + 1);
                        provincialCityMapper.insertSelective(provincialCity);
                    }
                }
            }
        }

    }
}
